﻿package net.wangit.dev;

import net.wangit.MapList;
import net.wangit.jdbc.DB;

public class ReferenceUtil {

	private static final String COUNT_NAME = "rowcount";
	private static final String SQL = "select t1.*,t2.eid,t2.n from UNIT t1,ELEMENT t2 where t2.c=? and t2.r=? and t1.uid=t2.uid";
	private static final String SQL_COUNT = "select count(*) rowcount from ELEMENT where c=? and r=?";
	private static final String SQL_TABLE = "select * from UNIT where t=? ";
	private static final String SQL_TABLE_COUNT = "select count(*) rowcount from UNIT where t=? ";
	private static final String SQL_ENUMERATION = "select t1.*,t2.eid,t2.n from UNIT t1,ELEMENT t2 where t2.c in (3,4,6,7,40,41,42,43,46,48,53) and t2.r=? and t1.uid=t2.uid";
	private static final String SQL_ENUMERATION_COUNT = "select count(*) rowcount from ELEMENT where c in (3,4,6,7,40,41,42,43,46,48,53) and r=? ";
	private static final String SQL_DP = "select * from UNIT where dpid=? ";
	private static final String SQL_INCREMENTOR = "select t1.*,t2.c,t2.cl from TABLE t1,COLUMN t2 where t2.g=? and t1.t=t2.t";

	public ReferenceUtil() {
	}

	public static MapList getTableReference(DB db, String tableName)
			throws Exception {
		return db.query(ReferenceUtil.SQL_TABLE, tableName, 2);
	}

	public static int getTableReferenceCount(DB db, String tableName)
			throws Exception {
		MapList list = db.query(ReferenceUtil.SQL_TABLE_COUNT, tableName, 2);
		return list.getRow(0).getInt(ReferenceUtil.COUNT_NAME, 0);
	}

	public static MapList getEnumerationReference(DB db, String eid)
			throws Exception {
		return db.query(ReferenceUtil.SQL_ENUMERATION, eid, 2);
	}

	public static int getEnumerationReferenceCount(DB db, String eid)
			throws Exception {
		MapList list = db.query(ReferenceUtil.SQL_ENUMERATION_COUNT, eid, 2);
		return list.getRow(0).getInt(ReferenceUtil.COUNT_NAME, 0);
	}

	public static MapList getDataPrivilegeReference(DB db, String dpid)
			throws Exception {
		return db.query(ReferenceUtil.SQL_DP, dpid, 2);
	}

	public static MapList getIncrementorReference(DB db, String generatorId)
			throws Exception {
		return db.query(ReferenceUtil.SQL_INCREMENTOR, generatorId, 2);
	}

	public static MapList getReference(DB db, String componentId, String id)
			throws Exception {
		return db.query(ReferenceUtil.SQL, new String[] { componentId, id },
				new int[] { 12, 2 });
	}

	public static int getReferenceCount(DB db, String componentId, String id)
			throws Exception {
		MapList list = db.query(ReferenceUtil.SQL_COUNT, new String[] {
				componentId, id }, new int[] { 12, 2 });
		return list.getRow(0).getInt(ReferenceUtil.COUNT_NAME, 0);
	}
}
